package com.ml4ai.backend.services.boot

import com.ml4ai.backend.services.RabbitmqService
import com.ml4ai.core.stack.mq.RabbitMQAgent
import lombok.extern.slf4j.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.CommandLineRunner
import org.springframework.stereotype.Component
import javax.annotation.PostConstruct
import java.util.function

import akka.actor._
import com.ml4ai.backend.services.actors.anys.FileTransfer2RabbitMQScheduleActor
import com.ml4ai.backend.services.capability.{Command, CommandReceiver}
import com.ml4ai.backend.utils.SpringUtils
import com.ml4ai.core.stack.parallel.RootControlActor

import collection.JavaConverters._

/**
  * Created by leecheng on 2018/11/25.
  */
@Component
@Slf4j object CommandExecutor {
}

@Component
@Slf4j class CommandExecutor extends CommandLineRunner {

  @Autowired var rabbitmqService: RabbitmqService = null
  private var rabbitMQAgent: RabbitMQAgent = null

  @PostConstruct def init(): Unit = {
    rabbitMQAgent = rabbitmqService.getRabbitMQAgent
  }

  @throws[Exception]
  override def run(strings: String*): Unit = {

    val root = RootControlActor("root")
    root(Props(new FileTransfer2RabbitMQScheduleActor), "file2queue")

    rabbitMQAgent.declareQueue("command", true, false, false, null)
    rabbitMQAgent.consumeText("command", 1, new function.Function[java.lang.String, java.lang.Boolean] {
      override def apply(t: java.lang.String): java.lang.Boolean = {
        def foo(command: Command) = {
          val commandReceivers = SpringUtils.getBeans(classOf[CommandReceiver]).values
          for (receive <- commandReceivers.asScala) {
            if (receive.getSupport equals command.getCommand) {
              receive execute command
            }
          }
          true
        }

        foo(new Command(t))
      }
    }

    )
  }

}
